package com.xialuo.study.flow;

import com.xialuo.study.agent.PlanningAgent;
import com.xialuo.study.agent.ReActAgent;
import com.xialuo.study.tools.PlanningTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class PlanningFlow {
    private static final Logger logger = LoggerFactory.getLogger(PlanningFlow.class);

    private final PlanningAgent planningAgent;
    private final ReActAgent reactAgent;
    private final PlanningTool planningTool;

    public PlanningFlow(PlanningAgent planningAgent, ReActAgent reactAgent, PlanningTool planningTool) {
        this.planningAgent = planningAgent;
        this.reactAgent = reactAgent;
        this.planningTool = planningTool;
    }

    /**
     * 执行完整的分析流程
     * @param dataDescription 数据描述
     * @param analysisGoal 分析目标
     * @param dataPath 数据文件路径
     * @return 分析结果
     */
    public String execute(String dataDescription, String analysisGoal, String dataPath) {
        try {
            // 1. 创建计划ID
            String planId = "plan_" + System.currentTimeMillis();
            logger.info("创建分析计划，ID: {}", planId);

            // 2. 使用PlanningAgent创建分析计划
            String planResult = planningAgent.createAnalysisPlan(dataDescription, analysisGoal, planId);
            logger.info("生成分析计划成功");

            // 3. 获取并执行计划中的每个步骤
            StringBuilder executionResults = new StringBuilder();

            while (true) {
                // 获取当前未完成的步骤
                StepInfo currentStep = findNextStep(planId);
                if (currentStep == null) {
                    logger.info("所有步骤已完成");
                    break; // 所有步骤已完成
                }

                logger.info("执行步骤 {}: {}", currentStep.index, currentStep.description);

                try {
                    // 更新步骤状态为进行中
                    planningTool.updateStepStatus(planId, currentStep.index, "IN_PROGRESS");

                    // 使用ReActAgent执行当前步骤
                    String stepResult = reactAgent.executeAnalysis(planResult, currentStep.description, dataPath);

                    // 更新步骤状态为已完成
                    planningTool.updateStepStatus(planId, currentStep.index, "COMPLETED");

                    // 记录步骤执行结果
                    executionResults.append("步骤 ").append(currentStep.index).append(" 结果: \n");
                    executionResults.append(stepResult).append("\n\n");

                    logger.info("步骤 {} 执行完成", currentStep.index);
                } catch (Exception e) {
                    // 如果步骤执行失败，标记为阻塞状态
                    planningTool.updateStepStatus(planId, currentStep.index, "BLOCKED");
                    String errorMsg = "步骤 " + currentStep.index + " 执行失败: " + e.getMessage();
                    executionResults.append(errorMsg).append("\n");
                    logger.error(errorMsg, e);
                    break; // 失败后停止执行
                }
            }

            // 4. 获取最终的计划状态
            String planDetails = planningTool.getPlan(planId);

            // 5. 生成最终报告
            return generateFinalReport(planDetails, executionResults.toString());
        } catch (Exception e) {
            logger.error("计划执行过程中发生错误", e);
            return "分析执行失败: " + e.getMessage();
        }
    }

    /**
     * 查找下一个需要执行的步骤
     */
    private StepInfo findNextStep(String planId) {
        try {
            String planDetails = planningTool.getPlan(planId);
            String[] lines = planDetails.split("\n");

            boolean inStepsSection = false;
            for (String line : lines) {
                if (line.trim().equals("步骤:")) {
                    inStepsSection = true;
                    continue;
                }

                if (inStepsSection && !line.trim().isEmpty()) {
                    // 寻找未开始或进行中的步骤
                    if (line.contains("[ ]") || line.contains("[→]")) {
                        int dotIndex = line.indexOf('.');
                        if (dotIndex > 0) {
                            try {
                                int stepIndex = Integer.parseInt(line.substring(0, dotIndex).trim());
                                String description = line.substring(line.indexOf(']') + 1).trim();
                                return new StepInfo(stepIndex, description);
                            } catch (NumberFormatException e) {
                                // 忽略非数字索引
                            }
                        }
                    }
                }
            }
            return null; // 没有找到需要执行的步骤
        } catch (Exception e) {
            logger.error("查找下一步骤时出错", e);
            return null;
        }
    }

    /**
     * 生成最终报告
     */
    private String generateFinalReport(String planDetails, String executionResults) {
        return String.format("""
                # 数据分析执行报告
                
                ## 计划概要
                %s
                
                ## 详细结果
                %s
                
                ## 结束时间
                %s
                """,
                planDetails,
                executionResults,
                java.time.LocalDateTime.now());
    }

    /**
     * 步骤信息内部类
     */
    private static class StepInfo {
        final int index;
        final String description;

        StepInfo(int index, String description) {
            this.index = index;
            this.description = description;
        }
    }
}
